package com.tanhua.dubbo.util;

import com.tanhua.domain.mongo.Sequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class IdGenerator {
    @Autowired
    private MongoTemplate mongoTemplate;
    @PostConstruct
    public void init() {
        //初始化“动态”的自增序列，从1000开始
        initSequence("publish", 1000);
        //初始化“视频”的自增序列，从1000开始
        initSequence("video", 1000);

    }
    private void initSequence(String type, Integer initValue) {
        Query query = new Query();
        Criteria criteria = Criteria.where("type").is(type);
        query.addCriteria(criteria);
        boolean exists = mongoTemplate.exists(query, Sequence.class);
        if (!exists) {
            Sequence sequence = new Sequence();
            sequence.setType(type);
            sequence.setValue(initValue);
            mongoTemplate.insert(sequence);
        }
    }
    public Long nextId(String type) {
        Query query = new Query();
        query.addCriteria(Criteria.where("type").is(type));

        Update update = new Update();
        update.inc("value", 1);

        //设置选项：先执行序列值自增，再获取自增后的值
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);

        //执行操作：修改然后获取修改后的新值
        Sequence sequence = mongoTemplate.findAndModify(query, update, options, Sequence.class);
        return sequence.getValue();
    }
}
